package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.util.FastDFSClient;
import com.changgou.file.util.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result fileUpload(MultipartFile multipartFile){
        try {
            if (multipartFile == null){
                throw new RuntimeException("文件不存在!");
            }
            //获取到文件的全名称
            String originalFilename = multipartFile.getOriginalFilename();

            //判断文件的全名称是否存在
            if (StringUtils.isEmpty(originalFilename)){
                throw new RuntimeException("文件不存在!");
            }
            //获取到文件的后缀名称
            String ext = originalFilename.substring(originalFilename.lastIndexOf("."));


            //获取到文件的内容
            byte[] content = multipartFile.getBytes();


            //获取到fastDFSFile对象
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename,content,ext);

            //上传文件操作
            String[] resultUrl = FastDFSClient.upload(fastDFSFile);

            //上传文件操作完成后,获取到返回值,将返回值进行组成
            String url = FastDFSClient.getTrackerUrl() + resultUrl[0] + "/" + resultUrl[1];

            return new Result(true,StatusCode.OK,"上传成功",url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,"上传失败");
        }
    }
}
